package com.zjp.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * 获取验证码
 */
@Controller
public class KaptController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @RequestMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生产验证码字符串并保存到session中
            String text = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute("vrifyCode", text);
            // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(text);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        // 将验证码以JPEG格式转换为字节数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        // 设置缓存控制，不允许缓存
        httpServletResponse.setHeader("Cache-Control", "no-store");
        // 设置缓存协议，不允许缓存
        httpServletResponse.setHeader("Pragma", "no-cache");
        // 设置过期时间，0表示不设置
        httpServletResponse.setDateHeader("Expires", 0);
        // 设置响应的内容类型为JPEG图片
        httpServletResponse.setContentType("image/jpeg");
        // 获取响应的输出流
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        // 将验证码写入输出流
        responseOutputStream.write(captchaChallengeAsJpeg);
        // 刷新输出流
        responseOutputStream.flush();
        // 关闭输出流
        responseOutputStream.close();
    }
}


